/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Salesman.Data;

import Salesman.City;
import Salesman.Distances;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.rlpw.lang.XMLClassResource;
import org.rlpw.swing.DefaultModel;
import org.rlpw.swing.Model;

/**
 *
 * @author weinpau
 */
public class DataProvider {

    private static Model<City> model;
    private static Distances dist;

    static {

        try {

            XMLClassResource xml = new XMLClassResource(DataProvider.class.getResourceAsStream("cities.xml"));
            model = new DefaultModel<City>(xml.getAllObjectsOf(City.class));

            CSVLoader csv = new CSVLoader("Streckenmatrix.csv");
            dist = new Distances(csv.data());


        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static Model<City> getCityData() {
        return model;
    }

    public static List<City> getInSimulationCities() {

        List<City> ls = new ArrayList<City>();
        for (City c : getCityData()) {
            if (c.isInSimulation()) {
                ls.add(c);
            }
        }
        return ls;
    }

    public static Distances getDistances() {
        return dist;
    }

    public static void setDistances(Distances dist) {
        DataProvider.dist = dist;
    }
}

class CSVLoader {

    private double[][] matrix;
    private String[] names;

    public CSVLoader(InputStream is) throws IOException {

        InputStreamReader fr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(fr);



        StringTokenizer str = new StringTokenizer(br.readLine(), ";");
        int length = str.countTokens() - 1;

        // init arrays
        names = new String[length];
        matrix = new double[length][length];


        // read names
        int i = 0;
        str.nextToken();
        while (str.hasMoreTokens()) {
            names[i++] = str.nextToken();
        }

        for (int j = 0; j < length; j++) {
            StringTokenizer st = new StringTokenizer(br.readLine(), ";");
            st.nextToken();
            for (int k = 0; k < length; k++) {

                String token = st.nextToken();

                token = token.replaceAll(",", ".").replaceAll(" ", "");
                double d = Double.POSITIVE_INFINITY;
                if (!token.equals("?")) {
                    d = Double.parseDouble(token);
                }

                matrix[j][k] = d;
            }
        }

        br.close();
        fr.close();

    }

    public CSVLoader(String resource) throws IOException {
        this(CSVLoader.class.getResourceAsStream(resource));
    }

    public double[][] data() {
        return matrix;
    }

    public String[] names() {
        return names;
    }
}
